<?php

namespace App\Http\Controllers\V1\Permission;

use App\Http\Requests\V1\UserRequest;
use App\Models\V1\AdminUser;
use App\Models\V1\BasicMaintainers;
use App\Models\V1\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;

class UsersController extends Controller
{

    /**
     * 显示用户列表页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.permission.users');
    }

    /**
     * 获取用户数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的用户数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的用户数据
        $data = $this->getUserList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $user = AdminUser::where('code',$item['code'])->first();
                    $is_admin = $user['is_admin'];
//                    if ($is_admin) {
//                        $formatItem['is_admin'] = '是';
//                    } else {
//                        $formatItem['is_admin'] = '否';
//                    }
                    $roles = $user->roles->toArray();
                    $role = '';
                    foreach ($roles as $temp_role) {
                        $role .= $temp_role['display_name'] . ',';
                    }
                    $role = rtrim($role, ',');
                    $formatItem['role'] = $role;
                    $formatItem['name'] = $item['name'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }


    /**
     * 进入单条用户数据显示界面（适用于查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $is_admin = $request->input('is_admin');
        $data['view'] = $request->input('view');
        $data['code'] = $request->input('code');
        if ($data['view'] === 'viewData') {
//            if ($is_admin === '是') {
                $currentMaintainer= $this->getMaintainerByCode($data['code']);
                if (empty($currentMaintainer) || !isset($currentMaintainer)) {
                    $currentMaintainer = new BasicMaintainers();
                    $currentMaintainer['code'] = 'admin';
                    $currentMaintainer['name'] = 'admin';
                    if ($data['view'] === 'viewData') {
                        $currentMaintainer['avatar'] = env('APP_URL') . '/images/default.jpg';
                    }
                    $data['itemData'] = $currentMaintainer;
                }else {
                    if ($data['view'] === 'viewData') {
                        $currentMaintainer['avatar'] = empty($currentMaintainer['avatar']) ? env('APP_URL') . '/images/default.jpg' : $currentStaff['avatar'];
                    }
                    $data['itemData'] = $currentMaintainer;
                }
                return view('v1.form.maintainer_item', $data);
//            } else {
//
//            }
        }elseif ($data['view'] === 'editData'){
            $data['is_admin'] = $is_admin;
//            if ($is_admin === '是') {
                $currentUser = $this->getMaintainerByCode($data['code']);
//            }else {
//            }
            $data['name'] = $currentUser['name'];
            $user = $this->getUserByCode($data['code']);
            $data['itemData'] = $user;
            //当前用户的角色
            $user_roles = $user->roles->toArray();
            $temp_roles = [];
            foreach ($user_roles as $user_role) {
                $temp_role = [
                    'id' => $user_role['id'],
                    'name' => $user_role['name'],
                    'display_name' => $user_role['display_name'],
                    'description' => $user_role['description'],
                    'created_at' => $user_role['created_at'],
                    'updated_at' => $user_role['updated_at'],

                ];
                array_push($temp_roles, $temp_role);
            }
            //用户当前已有角色
            $data['user_roles'] = $temp_roles;
            //所有角色
            $all_roles = Role::all()->toArray();
            $data['all_roles'] = $all_roles;

            return view('v1.permission.user_item', $data);
        }else{
        }

    }


    /**
     * 编辑用户基本信息
     *
     * @param Request $request
     * @return array
     */
    public function updateData(UserRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '用户信息更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateUser($request);

            $successFlag = $this->handleUpdate($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '用户信息更新成功！';
            }
        }

        return $response;
    }


    /**
     * 显示用户数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser['code'];

        return view('v1.form.upload_excel', $data);
    }


    /**
     * 删除用户基本信息
     *
     * @param UserRequest $request
     * @return array
     */
    public function deleteData(UserRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '用户代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateUser($request);

            // 删除用户信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '用户代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除用户基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '用户批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 删除用户角色信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '用户批量删除成功！';
            }
        }

        return $response;
    }


    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的用户列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */

    private function getUserList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = BasicMaintainers::orderBy('created_at', 'desc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = BasicMaintainers::where('name', 'like', '%' . $keywords . '%')->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 根据维护人员代码获取对应维护人员信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getMaintainerByCode($code)
    {
        $maintainer = BasicMaintainers::where('code', $code)->first();
        return $maintainer;
    }


    /**
     * 根据用户代码获取对应用户信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getUserByCode($code)
    {
        $user = AdminUser::where('code', $code)->first();
        return $user;
    }

    /**
     * 根据代码获取对应角色信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getRoleByCode($code)
    {
        $role = Role::where('name', $code)->first();
        return $role;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新用户信息验证请求
     *
     * @param UserRequest $request
     */
    private function validateUser(UserRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新用户信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request)
    {
        Log::info('user',['user'=>$request->all()]);

        $where = $request->input('code');
        $user = $this->getUserByCode($where);
        //更新用户角色信息
        //获取所有角色
        $all_roles = Role::all()->pluck('name');
        //当前用户的角色
//        $user_roles = $user->roles->toArray();
        foreach ($all_roles as $item) {
            $value = $request->input($item);
            $role = $this->getRoleByCode($item);
            if ($value === 'on' && !$user->hasRole($item)) {
                $user -> attachRole($role);
            }else if ($value !== 'on' && $user->hasRole($item)){
                $user -> detachRole($role);
            }else{
            }
        }

//        $updateData = [
//            'is_admin' => $request->input('is_admin'),
//        ];
//        $rspObj = AdminUser::where('code', $where)->update($updateData);
        return true;
    }

    /**
     * 处理删除用户角色信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $user = AdminUser::where('code', $code)
                    ->where(function ($query){
                        $query->where('code','<>','admin');
                    })->first();
                if ($user){
                    $user->detachRoles();
                }
            }
        } else { // 单条删除
            $user = AdminUser::where('code', $where)
                ->where(function ($query){
                    $query->where('code','<>','admin');
                })->first();
            if ($user){
                $user->detachRoles();
            }
        }
        return true;
    }

}

